import React from 'react'
import { Editor as MonacaEditor } from '@monaco-editor/react'
import type { OnMount,EditorProps } from '@monaco-editor/react'
import type { editor as MonacoEditor } from 'monaco-editor'
import { createATA } from './ata'

export interface EditorFile{
    name:string;
    language:string;
    value:string;
}

interface Props{
    file:EditorFile;
    onChange?:EditorProps['onChange'];
    options?: MonacoEditor.IStandaloneEditorConstructionOptions;
}

export default function Editor(props:Props) {

    const {file,onChange,options}=props

    const handleEditorMount: OnMount = (editor, monaco) => {
        monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
            jsx: monaco.languages.typescript.JsxEmit.Preserve,
            esModuleInterop: true,
            allowNonTsExtensions: true,
            target: monaco.languages.typescript.ScriptTarget.Latest,
            moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
            allowJs: true,
        })
        const ata = createATA((code, path) => {
            monaco.languages.typescript.typescriptDefaults.addExtraLib(code, `file://${path}`);
        })
        
        // 保留原来的ATA逻辑，但同时确保onChange被正确调用
        editor.onDidChangeModelContent(() => {
            ata(editor.getValue())
        })

    }

    return (
        <MonacaEditor
            path={file.name}
            height="100%"
            language={file.language}
            value={file.value}
            onMount={handleEditorMount}
            onChange={onChange} // 直接将onChange传递给MonacoEditor组件
            options={
                {
                    fontSize: 14,
                    scrollBeyondLastLine: false,
                    minimap: {
                        enabled: false,
                    },
                    scrollbar: {
                        verticalScrollbarSize: 6,
                        horizontalScrollbarSize: 6,
                    },
                    ...options,
                }
            }
        />
    )
}
